package com.ruoyi.capsule.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.capsule.utils.DateToCronConverter;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.service.ISysJobService;
import com.ruoyi.system.service.ISysUserService;
import org.quartz.SchedulerException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.capsule.domain.CapsuleData;
import com.ruoyi.capsule.service.ICapsuleDataService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 胶囊管理Controller
 *
 * @author wujiale
 * @date 2025-03-01
 */
@RestController
@RequestMapping("/capsule/data")
public class CapsuleDataController extends BaseController
{
    @Autowired
    private ICapsuleDataService capsuleDataService;

    @Autowired
    private ISysJobService iSysJobService;

    @Autowired
    private ISysUserService userService;


    //前台
    @GetMapping("/getCapsuleData")
    public AjaxResult getCapsuleData()
    {

        SysUser loginUser = SecurityUtils.getLoginUser().getUser();
        System.out.println(loginUser.toString()+"sdadsd");
        CapsuleData capsuleData = new CapsuleData();
        capsuleData.setUserId(loginUser.getUserId());

       return AjaxResult.success(capsuleDataService.selectCapsuleDataList(capsuleData));

    }
    /**
     * 查询胶囊管理列表
     */
//    @PreAuthorize("@ss.hasPermi('capsule:data:list')")
    @GetMapping("/list")
    public TableDataInfo list(CapsuleData capsuleData)
    {
        startPage();
        List<CapsuleData> list = capsuleDataService.selectCapsuleDataList(capsuleData);
        return getDataTable(list);
    }

    /**
     * 导出胶囊管理列表
     */
//    @PreAuthorize("@ss.hasPermi('capsule:data:export')")
    @Log(title = "胶囊管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CapsuleData capsuleData)
    {
        List<CapsuleData> list = capsuleDataService.selectCapsuleDataList(capsuleData);
        ExcelUtil<CapsuleData> util = new ExcelUtil<CapsuleData>(CapsuleData.class);
        util.exportExcel(response, list, "胶囊管理数据");
    }

    /**
     * 获取胶囊管理详细信息
     */
//    @PreAuthorize("@ss.hasPermi('capsule:data:query')")
    @GetMapping(value = "/{capsuleId}")
    public AjaxResult getInfo(@PathVariable("capsuleId") Long capsuleId)
    {
        return success(capsuleDataService.selectCapsuleDataByCapsuleId(capsuleId));
    }

    /**
     * 新增胶囊管理
     */
//    @PreAuthorize("@ss.hasPermi('capsule:data:add')")
    @Log(title = "胶囊管理", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody CapsuleData capsuleData) throws SchedulerException, TaskException {



        LoginUser loginUser = SecurityUtils.getLoginUser();
        System.out.println(loginUser+"1122");
        capsuleData.setUserId(loginUser.getUserId());
        SysUser sysUser = userService.selectUserById(loginUser.getUserId());
        //先看还有没有次数 没有直接返回
        if (sysUser.getDeptId() <= 0) {
            return AjaxResult.error("今日次数已用完，请明天再来");
        }else{
            sysUser.setDeptId(sysUser.getDeptId() - 1);
            userService.updateUser(sysUser);
        }



        //随机数结合时间戳生成随机id
        Random random = new Random();
        int RANDOM_BOUND = 1000;
        long timestamp = System.currentTimeMillis();
        int randomValue = random.nextInt(RANDOM_BOUND);
        capsuleData.setCapsuleId(timestamp * RANDOM_BOUND + randomValue);
        //创建定时任务
        SysJob job = new SysJob();
        //id
        job.setJobId(capsuleData.getCapsuleId());
        //任务名称
        job.setJobName("拾光胶囊");
        //任务组名
        job.setJobGroup("Capsule");
        //目标任务com.ruoyi.capsule.task.CapsuleTask.runTask('1740905785517311')

        String invokeTarget = "com.ruoyi.capsule.task.CapsuleTask.runTask("+"'" + capsuleData.getCapsuleId() + "'" + ")";
        job.setInvokeTarget(invokeTarget);
        //crontab表达式
        job.setCronExpression(DateToCronConverter.convertDateToCron(capsuleData.getUnlockTime()));
        //执行失败时隔一段时间再执行一次
        job.setMisfirePolicy("2");
        //并发执行
        job.setConcurrent("1");
        //插入任务
        iSysJobService.insertJob(job);
        //开启任务
        job.setStatus("0");
        iSysJobService.changeStatus(job);
        return toAjax(capsuleDataService.insertCapsuleData(capsuleData));
    }

    /**
     * 修改胶囊管理
     */
    @PreAuthorize("@ss.hasPermi('capsule:data:edit')")
    @Log(title = "胶囊管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CapsuleData capsuleData)
    {
        return toAjax(capsuleDataService.updateCapsuleData(capsuleData));
    }

    /**
     * 删除胶囊管理
     */
//    @PreAuthorize("@ss.hasPermi('capsule:data:remove')")
    @Log(title = "胶囊管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{capsuleIds}")
    public AjaxResult remove(@PathVariable Long[] capsuleIds)
    {
        return toAjax(capsuleDataService.deleteCapsuleDataByCapsuleIds(capsuleIds));
    }
}
